import axios, { type AxiosError, type InternalAxiosRequestConfig } from 'axios'
import { useAuthStore } from '@/stores/auth'
import router from '@/router'

// 确保在构建时已经设置了 VITE_API_BASE_URL 环境变量
const api = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL || 'https://ms3191793zs.vicp.fun/api',
  timeout: 30000,
})

// 添加日志以调试
console.log('API Base URL:', import.meta.env.VITE_API_BASE_URL || '使用默认 API 地址')

// 请求拦截器 - 添加token
api.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    try {
      const authStore = useAuthStore()
      if (authStore?.accessToken) {
        config.headers.Authorization = `Bearer ${authStore.accessToken}`
      }
    } catch (error) {
      // 如果store未初始化，忽略错误
      console.warn('Auth store not available:', error)
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器 - 处理token刷新
let isRefreshing = false
let failedQueue: Array<{
  resolve: (value?: any) => void
  reject: (reason?: any) => void
}> = []

const processQueue = (error: any, token: string | null = null) => {
  failedQueue.forEach((prom) => {
    if (error) {
      prom.reject(error)
    } else {
      prom.resolve(token)
    }
  })
  failedQueue = []
}

api.interceptors.response.use(
  (response) => {
    return response
  },
  async (error: AxiosError) => {
    const originalRequest = error.config as InternalAxiosRequestConfig & { _retry?: boolean }

    // 如果是401错误且未重试过，并且不是刷新token的请求
    if (error.response?.status === 401 && !originalRequest._retry && originalRequest.url !== '/auth/refresh') {
      if (isRefreshing) {
        // 如果正在刷新token，将请求加入队列
        return new Promise((resolve, reject) => {
          failedQueue.push({ resolve, reject })
        })
          .then((token) => {
            if (originalRequest.headers && token) {
              originalRequest.headers.Authorization = `Bearer ${token}`
            }
            return api(originalRequest)
          })
          .catch((err) => {
            return Promise.reject(err)
          })
      }

      originalRequest._retry = true
      isRefreshing = true

      try {
        const authStore = useAuthStore()
        const success = await authStore.refreshAccessToken()

        if (success && authStore.accessToken) {
          processQueue(null, authStore.accessToken)
          isRefreshing = false
          if (originalRequest.headers) {
            originalRequest.headers.Authorization = `Bearer ${authStore.accessToken}`
          }
          return api(originalRequest)
        } else {
          processQueue(new Error('刷新token失败'), null)
          isRefreshing = false
          authStore.clearAuth()
          router.push('/login').catch(() => {})
          return Promise.reject(error)
        }
      } catch (err) {
        isRefreshing = false
        processQueue(new Error('刷新token失败'), null)
        return Promise.reject(error)
      }
    }

    return Promise.reject(error)
  }
)

export default api

